#include "EchoServer.h"
#include <iostream>

using std::cout;
using std::endl;

EchoServer::EchoServer(size_t threadNum, size_t queSize, const string &ip, unsigned short port)
: _pool(threadNum, queSize)
, _server(ip, port)
{

}

EchoServer::~EchoServer()
{

}

void EchoServer::start()
{
    _pool.start();
    //启动服务器之前：注册回调函数
    using namespace std::placeholders;
    _server.setAllCallback(std::bind(&EchoServer::onNewConnection,this,_1),
                           std::bind(&EchoServer::onMessage,this,_1),
                           std::bind(&EchoServer::onClose,this,_1));
    _server.start();
}

void EchoServer::stop()
{
    _pool.stop();
    _server.stop();
}

void EchoServer::onNewConnection(const TcpConnectionPtr &con)
{
    cout << con->toString() << " has connected." << endl;
}

void EchoServer::onMessage(const TcpConnectionPtr &con)
{
    const string msg = con->receive();
    cout << ">>receive from client :" << msg << endl;
    /* con->send("server has receive the message\n"); */

    //交给线程池
    MyTask task(msg, con);
    _pool.addTask(std::bind(&MyTask::process, task));
}

void EchoServer::onClose(const TcpConnectionPtr &con)
{
    cout << con->toString() << " has closed." << endl;
}
